package com.hup.sidebar.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.hup.sidebar.R;
import com.hup.sidebar.framework.util.ToastUtil;

/**
 * https://developer.android.com/about/versions/12/behavior-changes-12#notification-trampolines
 * 问题:
 * [Android 12, API 31, 部分厂商可能>12 ]后, 安卓系统限制,
 * 调用 context.startActivity(packageManager.getLaunchIntentForPackage(packageName)) 时, 可能会有"确认打开弹窗"
 * 触发条件:
 * - 目标app为: 非系统app
 * - 调用方为: 非前台界面, 服务,悬浮窗等
 * 解决方案:
 * - 仅针对系统app
 * - 过程:先跳转到本activity, 再打开目标app
 * 注意:
 * - 不能完全阻止弹窗, 如:首次跳转; 退出目标app后, 从[最近app]打开目标app等
 *
 * @author hugan
 * @date 2025/11/12
 */
public class TrampolineActivity extends Activity {
    private static final String TAG = TrampolineActivity.class.getSimpleName();

    private static final String KEY_APP = "APP";

    /**
     * 按需调用, 如 if (android.os.Build.VERSION.SDK_INT >= 30)
     */
    public static void startActivityTrampoline(Context context, String packageName) {
        Intent intent = new Intent(context, TrampolineActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);//不显示在[最近app]
        intent.putExtra(KEY_APP, packageName);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if (intent != null) {
            String app = intent.getStringExtra(KEY_APP);
            if (app != null) {
                //Log.i(TAG, "onCreate: app=" + app);

                PackageManager packageManager = this.getPackageManager();
                Intent target = packageManager.getLaunchIntentForPackage(app);
                if (target != null) {
                    /*
                    加速切换画面, 不用动画;
                    配合 android:theme="@style/NoAnimationTheme"
                    flyme有时无效,
                     */
                    overridePendingTransition(0, 0);
                    this.startActivity(target);
                    overridePendingTransition(0, 0);
                } else {
                    Log.e(TAG, "onCreate: Intent为空=" + app);
                    ToastUtil.short_(String.format(getString(R.string.launch_app_failure), app));
                }
            }
        }
        //马上退出
        finish();
    }

}
